//
//  NvFilmUploadViewController.m
//  NvSellerShow
//
//  Created by xuewen on 2017/2/13.
//  Copyright © 2017年 Meicam. All rights reserved.
//

#import "NvFilmUploadViewController.h"
#import "NvsLiveWindow.h"
#import "NvPlaySlider.h"
#import "NvFilmViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "NvPlayer.h"
#import "UAProgressView.h"
#import "NvUploadManager.h"

@interface NvFilmUploadViewController ()


@property float busyIndicatorImageRotationAngle;

@property (strong, nonatomic) NvPlayer *player;
@property (strong, nonatomic) UIView *uploadView;

@property (strong, nonatomic) UILabel *stateLabel;
@property (strong, nonatomic) UAProgressView *progressView;
@property (strong, nonatomic) UIView *midInfoView;
@property (strong, nonatomic) UIButton *backBtn;

@end

@implementation NvFilmUploadViewController

- (UIView *)midInfoView {
    if (!_midInfoView) {
        _midInfoView = [[UIView alloc]init];
        _midInfoView.backgroundColor = [UIColor whiteColor];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH, 25)];
        titleLabel.text = @"作品信息";
        titleLabel.textColor = UIColorHexRGB(@"#666666");
        titleLabel.font = [UIFont systemFontOfSize:14];
        [_midInfoView addSubview:titleLabel];
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, titleLabel.bottom_LL, SCREEN_WIDTH, 1)];
        line.backgroundColor = UIColorHexRGB(@"#F1F1F1");
        [_midInfoView addSubview:line];
        
        UILabel *nameLabel = [[UILabel alloc]init];
        nameLabel.frame = CGRectMake(15,line.bottom_LL+15, SCREEN_WIDTH-30, 20);
        nameLabel.numberOfLines = 2;
        nameLabel.textColor = UIColorHexRGB(@"#333333");
        nameLabel.font = [UIFont systemFontOfSize:14];
        nameLabel.text = self.uploadModel.fileName;
        CGRect rect = [self.uploadModel.fileName boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-30, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil];
        nameLabel.frame = CGRectMake(15, line.bottom_LL+15, SCREEN_WIDTH-30, rect.size.height);
        [_midInfoView addSubview:nameLabel];
        
        UILabel *videoDurLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, nameLabel.bottom_LL+5, SCREEN_WIDTH-30, 20)];
        videoDurLabel.text = self.uploadModel.fileDuration;
        videoDurLabel.textColor = UIColorHexRGB(@"#666666");
        videoDurLabel.font = [UIFont systemFontOfSize:12];
        [_midInfoView addSubview:videoDurLabel];
        
        _midInfoView.frame = CGRectMake(0, _player.bottom_LL - 64 + 15, SCREEN_WIDTH, videoDurLabel.bottom_LL + 10);
        _midInfoView.layer.borderColor = [[UIColor colorWithRed:214.0f/255 green:214.0f/255 blue:214.0f/255 alpha:1.0f] CGColor];
        _midInfoView.layer.borderWidth = 0.5;
        _midInfoView.layer.cornerRadius = 0;
        _midInfoView.layer.masksToBounds = YES;
    }
    return _midInfoView;
}

- (void)initUploadView {
    self.uploadView = [[UIView alloc]initWithFrame:CGRectMake(self.view.centerX_LL - 100, self.view.centerY_LL-100-64, 200, 200)];
    self.uploadView.layer.borderWidth = 2.0;
    self.uploadView.layer.borderColor = [UIColor orangeColor].CGColor;
    self.uploadView.layer.cornerRadius = 60;
    self.uploadView.backgroundColor = [UIColor lightGrayColor];
    
    self.progressView = [[UAProgressView alloc]initWithFrame:CGRectMake(40, 10, 120, 120)];
    self.progressView.tintColor = UIColorHexRGB(@"#5bc2e5");
    self.progressView.borderWidth = 1.0;
    self.progressView.lineWidth = 2.0;
    self.progressView.fillOnTouch = YES;
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80.0, 30.0)];
    textLabel.font = [UIFont systemFontOfSize:24];
    
    textLabel.textAlignment = NSTextAlignmentCenter;
    textLabel.textColor = UIColorHexRGB(@"#5bc2e5");
    textLabel.backgroundColor = [UIColor clearColor];
    textLabel.text = @"0 %";
    self.progressView.centralView = textLabel;
    self.progressView.progressChangedBlock = ^(UAProgressView *progressView, CGFloat progress){
        [(UILabel *)progressView.centralView setText:[NSString stringWithFormat:@"%2.0f%%", progress * 100]];
    };
    [self.uploadView addSubview:self.progressView];
    
    self.stateLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.progressView.bottom_LL+10, 200, 30)];
    self.stateLabel.textColor = [UIColor whiteColor];
    self.stateLabel.text = @"视频上传中,请稍后...";
    self.stateLabel.textAlignment = NSTextAlignmentCenter;
    self.stateLabel.font = [UIFont systemFontOfSize:14];
    [self.uploadView addSubview:self.stateLabel];
    
    [self.view addSubview:self.uploadView];
    [self.uploadView setHidden:YES];

}

- (void)initPlayerView {
    self.player = [NvPlayer palyer];
    if (self.uploadModel.scale == NvSSVideoCreateScaleHorizontal) {
        self.player.frame = CGRectMake(0, 9.0/32 *SCREEN_WIDTH-64, SCREEN_WIDTH, 9.0/16 *SCREEN_WIDTH +64);
    } else {
        self.player.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH+64);
    }
    [self.player setOldFrame:self.player.frame];
    [self.view addSubview:self.player];
    [self.player updatePlayerWith:self.uploadModel.filePath];
}

- (void)initBottomLoadView {
    UIView *botLoadView = [[UIView alloc]init];
    botLoadView.backgroundColor = [UIColor whiteColor];
    botLoadView.frame = CGRectMake(0, self.view.bounds.size.height - 80-64, SCREEN_WIDTH, 80);
    botLoadView.layer.borderColor = [[UIColor colorWithRed:214.0f/255 green:214.0f/255 blue:214.0f/255 alpha:1.0f] CGColor];
    botLoadView.layer.borderWidth = 0.5;
    botLoadView.layer.cornerRadius = 0;
    botLoadView.layer.masksToBounds = YES;
    
    UIButton *uploadButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH -20, 60)];
    [uploadButton setTitle:@"立即上传" forState:UIControlStateNormal];
    [uploadButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [uploadButton setBackgroundColor:[UIColor colorWithRed:1/255.0 green:88/255.0 blue:255/255.0 alpha:1/1.0]];
    [uploadButton addTarget:self action:@selector(doUploadEvent:) forControlEvents:UIControlEventTouchUpInside];
    [botLoadView addSubview:uploadButton];
    [self.view addSubview:botLoadView];
}

- (void)initNavigationBarView {
    self.backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    [self.backBtn setBackgroundImage:[UIImage imageFromBundle:@"back_icon"] forState:UIControlStateNormal];
    [self.backBtn addTarget:self action:@selector(doClickBackEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.backBtn];
    
    self.title = @"立即上传";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColorHexRGB(@"#F5F5F5");
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self initNavigationBarView];
    [self initPlayerView];
    [self.view addSubview:self.midInfoView];
    [self initBottomLoadView];
    [self initUploadView];
    [self.view setNeedsLayout];
}

- (void)doClickBackEvent:(UIButton *)sender {
    [self.player pause];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)doUploadEvent:(UIButton *)sender {
    [self.player pause];
    [self doUploadWork];
}

- (void)doUploadWork {
    NSString *curNet = [self currentNetWork];
    if ([curNet isEqualToString:@"NO-WIFI"]) {
        [Utils showMessageAlertWithTitle:@"上传失败" message:@"当前无网络"];
        return;
    } else if ([curNet isEqualToString:@"WIFI"]) {
        [self uploadViewShowWith:NO];
        [self.progressView setProgress:0 animated:YES];
        self.stateLabel.text = @"正在上传...";
        NvUploadManager *manager = [NvUploadManager defaultManager];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [manager uploadTaskfromFile:[self.uploadModel changeToDictionary] progressValue:^(NSProgress *progress) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    CGFloat curProgress = 1.0* progress.completedUnitCount/progress.totalUnitCount ;
                    [self.progressView setProgress:curProgress animated:YES];
                });
            } completionHandler:^(NSError *error) {
                
                if (error != nil) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [Utils showMessageAlertWithTitle:@"上传失败" message:[NSString stringWithFormat:@"%@",error.localizedDescription] actionTitle:@"确定" actionHandler:^{
                            [self.uploadView setHidden:YES];
                            self.view.userInteractionEnabled = YES;
                            self.backBtn.userInteractionEnabled = YES;
                        }];
                    });
                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.uploadView setHidden:YES];
                        self.view.userInteractionEnabled = YES;
                        self.backBtn.userInteractionEnabled = YES;
                        [Utils showConfirmAlertWithTitle:@"上传成功" message:@"" firstActionTitle:@"继续拍摄" firstAction:^{
                            for(UIViewController *controller in self.navigationController.viewControllers) {
                                if([controller isKindOfClass:[MsViewController class]]){
                                    MsViewController *owr = (MsViewController *)controller;
                                    [self.navigationController popToViewController:owr animated:YES];
                                }
                            }
                        } secondActionTitle:@"选择视频" secondAction:^{
                            for(UIViewController *controller in self.navigationController.viewControllers) {
                                if([controller isKindOfClass:[MsViewController class]]){
                                    MsViewController *owr = (MsViewController *)controller;
                                    NSInteger index = [self.navigationController.viewControllers indexOfObject:owr];
                                    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:index-1] animated:YES];
                                }
                            }
                        }];
                    });
                }
            }];
        });
    } else {
        [Utils showConfirmAlertWithTitle:@"流量提醒" message:@"您正在使用移动网络,是否上传" yesTitle:@"确定" yesAction:^{
            [self uploadViewShowWith:NO];
            [self.progressView setProgress:0 animated:YES];
            self.stateLabel.text = @"正在上传...";
            NvUploadManager *manager = [NvUploadManager defaultManager];
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [manager uploadTaskfromFile:[self.uploadModel changeToDictionary] progressValue:^(NSProgress *progress) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        CGFloat curProgress = 1.0* progress.completedUnitCount/progress.totalUnitCount ;
                        [self.progressView setProgress:curProgress animated:YES];
                    });
                } completionHandler:^(NSError *error) {
                    
                    if (error != nil) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [Utils showMessageAlertWithTitle:@"上传失败" message:[NSString stringWithFormat:@"%@",error.localizedDescription] actionTitle:@"确定" actionHandler:^{
                                [self.uploadView setHidden:YES];
                                self.view.userInteractionEnabled = YES;
                                self.backBtn.userInteractionEnabled = YES;
                            }];
                        });
                    } else {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.uploadView setHidden:YES];
                            self.view.userInteractionEnabled = YES;
                            self.backBtn.userInteractionEnabled = YES;
                            [Utils showConfirmAlertWithTitle:@"上传成功" message:@"" firstActionTitle:@"继续拍摄" firstAction:^{
                                for(UIViewController *controller in self.navigationController.viewControllers) {
                                    if([controller isKindOfClass:[MsViewController class]]){
                                        MsViewController *owr = (MsViewController *)controller;
                                        [self.navigationController popToViewController:owr animated:YES];
                                    }
                                }
                            } secondActionTitle:@"选择视频" secondAction:^{
                                for(UIViewController *controller in self.navigationController.viewControllers) {
                                    if([controller isKindOfClass:[MsViewController class]]){
                                        MsViewController *owr = (MsViewController *)controller;
                                        NSInteger index = [self.navigationController.viewControllers indexOfObject:owr];
                                        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:index-1] animated:YES];
                                    }
                                }
                            }];
                        });
                    }
                }];
            });
        } cancelTitle:@"取消" cancelAction:nil];
    }
}

- (void)uploadViewShowWith:(BOOL)isShow {
    [self.uploadView setHidden:isShow];
    [self.backBtn setUserInteractionEnabled:isShow];
    [self.view setUserInteractionEnabled:isShow];
}

- (void)dealloc {
    self.player = nil;
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    NSLog(@"全屏播放结束");
}

- (NSString *)currentNetWork {
    UIApplication *app = [UIApplication sharedApplication];
    
    NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    
    int type = 0;
    for (id child in children) {
        if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
        }
    }
    switch (type) {
        case 1:
            return @"2G";
            break;
        case 2:
            return @"3G";
        case 3:
            return @"4G";
        case 5:
            return @"WIFI";
        default:
            return @"NO-WIFI";//代表未知网络
            break;
    }
}
@end
